package com.int_tech.control.controller;

import com.int_tech.car.dao.CarDao;
import com.int_tech.car.entity.Car;
import com.int_tech.control.dao.RateDao;
import com.int_tech.control.dao.SocketGetResourceDao;
import com.int_tech.control.dao.SocketLogDao;
import com.int_tech.control.dao.SocketLogSendDao;
import com.int_tech.control.entity.Rate;
import com.int_tech.control.entity.SocketGetResource;
import com.int_tech.control.entity.SocketLog;
import com.int_tech.control.entity.SocketLogSend;
import com.int_tech.mession.dao.MessionDao;
import com.int_tech.mession.entity.Mession;
import com.int_tech.messionLog.dao.MessionLogDao;
import com.int_tech.messionLog.entity.MessionLog;
import com.int_tech.station.dao.StationDao;
import com.int_tech.station.entity.Station;
import com.int_tech.user.dao.UserDao;
import com.int_tech.user.entity.User;
import com.int_tech.utils.DateTool;
import com.int_tech.utils.MessageHelp;
import com.int_tech.utils.RateUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by liubch on 2017/9/29.
 */
@Controller
@RequestMapping("cont")
public class contController {
    @Autowired
    private MessionLogDao messionLogDao;
    @Autowired
    private MessionDao messionDao;

    @Autowired
    private StationDao stationDao;

    @Autowired
    private RateDao rateDao;

    @Autowired
    private CarDao carDao;

    @Autowired
    private SocketLogDao socketLogDao;

    @Autowired
    private SocketLogSendDao socketLogSendDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private SocketGetResourceDao socketGetResourceDao;

    /**
     * 场站监控
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/stationControl", method = RequestMethod.GET)
    public String stationControl(Model model, HttpServletRequest request) {

        //通过用户登录id查询场站信息
        /*int clientId = (int) request.getSession().getAttribute("uid");*/
        int clientId = -99;

        try
        {
            clientId = (int) request.getSession().getAttribute("uid");
        }
        catch (Exception e)
        {
            return "car/retry";
        }

        //新场站列表，需要过滤掉没有车辆的场站
        List<Station> stations = new ArrayList<>();

        if(clientId == 1)
        {
            List<Station> stationList = stationDao.findAll();
            for (Station station : stationList)
            {
                int count = carDao.countByStationIdAndIsDel(station.getId(),0);
                station.setCarCount(count);

                if(count > 0)
                {
                    stations.add(station);
                }
            }

            model.addAttribute("stationList",stationList);
        }
        else
        {
            List<Station> stationList = stationDao.findByClientId(clientId);

            if(stationList == null || stationList.size() == 0)
            {
                User user = userDao.findById(clientId);

                String stationsa[];

                //一个用户多个场站
                if(user.getStationId().contains(","))
                {
                    stationList = new ArrayList<>();

                    stationsa = user.getStationId().split(",");

                    for(String sid : stationsa)
                    {
                        Station station = stationDao.findById(Integer.parseInt(sid));

                        stationList.add(station);
                    }
                }
                else
                {
                    Station station = stationDao.findById(Integer.parseInt(user.getStationId()));

                    stationList = new ArrayList<>();

                    stationList.add(station);
                }
            }


            List<Car> carList = carDao.findCarByIsDel(0);

            for (Station station : stationList)
            {
                int count = 0;
                for(Car car : carList)
                {
                    if(station.getId() == car.getStationId())
                    {
                        count++;
                    }
                }
                station.setCarCount(count);
//                stations.add(station);
                if(count > 0)
                {
                    stations.add(station);
                }
            }
            model.addAttribute("stationList",stations);
        }

        return "/control/stationControl";
    }

    /**
     * 装载率查询首页
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/rateCheck", method = RequestMethod.GET)
    public String rateCheck(Model model, HttpServletRequest request) {

        int clientId = -99;

        List<Car> carList = carDao.findCarByIsDel(0);

        try
        {
            clientId = (int) request.getSession().getAttribute("uid");
        }
        catch (Exception e)
        {
            return "car/retry";
        }

        if(clientId == 1)
        {

            //新场站列表，需要过滤掉没有车辆的场站
            List<Station> stations = new ArrayList<>();

            List<Station> stationList = stationDao.findAll();
            for (Station station : stationList)
            {
                int count = 0;
                for(Car car : carList)
                {
                    if(station.getId() == car.getStationId())
                    {
                        count++;
                    }
                }

                if(count > 0)
                {
                    station.setCarCount(count);
                    stations.add(station);
                }
            }
            model.addAttribute("stationList",stations);
        }
        else
        {
            //新场站列表，需要过滤掉没有车辆的场站
            List<Station> stations = new ArrayList<>();

            List<Station> stationList = stationDao.findByClientId(clientId);

            if(stationList == null || stationList.size() == 0)
            {
                User user = userDao.findById(clientId);

                String stationsa[];

                //一个用户多个场站
                if(user.getStationId().contains(","))
                {
                    stationList = new ArrayList<>();

                    stationsa = user.getStationId().split(",");

                    for(String sid : stationsa)
                    {
                        Station station = stationDao.findById(Integer.parseInt(sid));

                        stationList.add(station);
                    }
                }
                else
                {
                    Station station = stationDao.findById(Integer.parseInt(user.getStationId()));

                    stationList = new ArrayList<>();

                    stationList.add(station);
                }
            }


            for (Station station : stationList)
            {
                int count = 0;
                for(Car car : carList)
                {
                    if(station.getId() == car.getStationId())
                    {
                        count++;
                    }
                }
                if(count > 0)
                {
                    station.setCarCount(count);
                    stations.add(station);
                }
            }
            model.addAttribute("stationList",stations);
        }
        return "/control/rate";
    }


    /**
     * socket请求数据存储信息
     * @param request
     * @param requestBody
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/saveSocketLog", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String saveSocketLog(HttpServletRequest request,@RequestBody String requestBody) throws UnsupportedEncodingException
    {
        try
        {
            String requestJson = "";
            requestJson = URLDecoder.decode(requestBody, "utf-8");
            requestJson = new String(requestJson.getBytes("ISO-8859-1"),"UTF-8");
            String data = requestJson;

            System.out.print(data);

            data = data.trim();
            data = data.replaceAll(" ","");

            //存储原始数据
            SocketGetResource socketGetResource = new SocketGetResource();

            socketGetResource.setDataString(data);
            socketGetResource.setCreateTime(new Date());
            socketGetResource.setStatus(0);

            socketGetResourceDao.save(socketGetResource);


            String[] datalog = data.split(",");

            //获取硬件时间
            String yjTime = datalog[6];

            //创建时间
            String year = yjTime.substring(0,4);
            String month = yjTime.substring(4,6);
            String day = yjTime.substring(6,8);
            String hour = yjTime.substring(8,10);
            String min = yjTime.substring(10,12);
            String second = yjTime.substring(12,14);

            String dt = year+"-"+month+"-"+day+" "+hour+":"+min+":"+second;

            Date cd = DateTool.string2Date(dt,"yyyy-MM-dd HH:mm:ss");


            Calendar cal = Calendar.getInstance();
            cal.setTime(cd);//date 换成已经已知的Date对象
            cal.add(Calendar.HOUR_OF_DAY, 8);// before 8 hour
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println(format.format(cal.getTime()));

            cd = DateTool.string2Date(format.format(cal.getTime()),"yyyy-MM-dd HH:mm:ss");

            SocketLog log = new SocketLog();
            log.setCreateTime(cd);
            log.setDataString(data);
            log.setStatus(0);

            String daString = "";

            if("A2".equals(datalog[0])||"A4".equals(datalog[0]))
            {
                String x = datalog[8];
                String y = datalog[7];

                String url = "http://api.map.baidu.com/geoconv/v1/?coords="+x+","+y+"&from=1&to=5&ak=TsCP2qXsP0RLmchQ7cQYyQa1C5Cwh4er";

                String result = this.getJson(url);

                JSONObject object = JSONObject.fromObject(result);

                JSONArray result1 = (JSONArray) object.get("result");

                object = result1.getJSONObject(0);

                x = String.valueOf((Double) object.get("x"));
                y = String.valueOf((Double) object.get("y"));

                for (int i = 0;i<datalog.length;i++)
                {
                    if(StringUtils.isEmpty(daString))
                    {
                        daString += datalog[i];
                    }
                    else
                    {
                        if(i == 7)
                        {
                            daString += ","+y;
                        }
                        else if(i == 8)
                        {
                            daString += ","+x;
                        }
                        else
                        {
                            daString += ","+datalog[i];
                        }
                    }
                }

                log.setDataString(data);
            }



            log.setServiceType(datalog[1]);
            log.setCode(datalog[0]);
            log.setCarNumber(datalog[2]);

            /*if(data.contains("open")||data.contains("close"))
            {
                log.setType(1);
                String carNumber = data.split(",")[0];
                log.setCarNumber(carNumber);
            }
            else
            {
                log.setType(2);
                String carNumber = data.split(",")[1];
                log.setCarNumber(carNumber);
            }*/

            socketLogDao.save(log);



            SocketLogSend socketLogSend = new SocketLogSend();

            socketLogSend.setCreateTime(cd);
            if("A2".equals(datalog[0])||"A4".equals(datalog[0]))
            {
                socketLogSend.setDataString(daString);
            }
            else
            {
                socketLogSend.setDataString(data);
            }

            socketLogSend.setStatus(0);
            socketLogSend.setServiceType(datalog[1]);
            socketLogSend.setCode(datalog[0]);
            socketLogSend.setCarNumber(datalog[2]);

            socketLogSendDao.save(socketLogSend);

            return "ok";
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return "fail";
        }
    }

    /**
     * 查询socket日志
     * @param request
     * @return
     */
    @RequestMapping(value = "/checkSocketLog", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String checkSocketLog(HttpServletRequest request,String key) throws UnsupportedEncodingException
    {

       /* if(StringUtils.isEmpty(createTime)||StringUtils.isEmpty(endTime))
        {
            String c = DateTool.Date2String(new Date(),"yyyy-MM-dd") + " 00:00:00";
            endTime = DateTool.Date2String(new Date(),"yyyy-MM-dd HH:mm:ss");
            Date cd = DateTool.string2Date(c,"yyyy-MM-dd HH:mm:ss");
            Date ed = DateTool.string2Date(endTime,"yyyy-MM-dd HH:mm:ss");

            List<SocketLog> socketLogs = socketLogDao.findLogs(cd,ed,key);

            JSONArray jsonArray = JSONArray.fromObject(socketLogs);

            return jsonArray.toString();
        }
        else
        {
            Date cd = DateTool.string2Date(createTime +  " 00:00:00","yyyy-MM-dd HH:mm:ss");
            Date ed = DateTool.string2Date(endTime +  " 23:59:59","yyyy-MM-dd HH:mm:ss");

            List<SocketLog> socketLogs = socketLogDao.findLogs(cd,ed,key);

            JSONArray jsonArray = JSONArray.fromObject(socketLogs);

            return jsonArray.toString();
        }*/
//        List<SocketLog> socketLogs = socketLogDao.findByDataStringLikeOrderByCreateTimeDesc(key);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -2);
        date = calendar.getTime();
        List<SocketLog> socketLogs = socketLogDao.findByDataStringLikeAndCreateTimeAfterOrderByCreateTimeDesc(key,date);

        String[] data = new String[socketLogs.size()];

        int m = 0;
        for (SocketLog socketLog : socketLogs)
        {
            socketLog.setDataString(socketLog.getDataString().trim());
            data[m] = socketLog.getDataString();
            m++;
        }

        JSONArray jsonArray = JSONArray.fromObject(socketLogs);

        return jsonArray.toString();


    }

    /**
     * 电子锁接收解析存储
     * @param request
     * @param requestBody
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/checkMession", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String checkMession(HttpServletRequest request,@RequestBody String requestBody) throws UnsupportedEncodingException
    {

        String requestJson = "";
        requestJson = URLDecoder.decode(requestBody, "utf-8");
        requestJson = new String(requestJson.getBytes("ISO-8859-1"),"UTF-8");
        String data = requestJson;

        System.out.print(data);

//        data = "020123427,open,201706010599476,1,0001,20170601051910.000,116.580853,40.134459,0001";




        //处理数据，存储
        MessionLog messionLog = MessageHelp.messionHelp(data);

        //查询最大任务递增码
        //车牌区号
        String areaNumber = messionLog.getCarNumber().substring(0,3);
        String time = messionLog.getRtcTime().substring(0, 8);


        //判断是否为新任务

        List<MessionLog> messionLogList = messionLogDao.findByMessionNumberLike(areaNumber+time,messionLog.getCarNumber());

        //任务编码,任务编号
        String messionCode = "";
        String messionNumber = "";

        //如果新表，任务编码为0001
        Long count = messionLogDao.count();

        if(count == 0)
        {
            messionCode = "0001";
        }

        //没有该任务
        //如果是第一个任务，直接加
        if("0001".equals(messionCode))
        {
            messionNumber = areaNumber+time+messionCode;
            messionLog.setCreateTime(new Date());
            messionLog.setUpdateTime(new Date());
            messionLog.setMessionCount(messionCode);
            String rtcTime = messionLog.getRtcTime();

            Mession mession = new Mession();
            mession.setMessionNumber(messionNumber);
            mession.setCreateTime(new Date());
            mession.setUpdateTime(new Date());
            mession.setCarNumber(messionLog.getCarNumber());
            //如果为open且为新任务则为装车开始
            if (messionLog.getDoorMessage().equals("open")){
                mession.setStartOpenDoorTime(new Date());
                messionDao.save(mession);
            }

        }
        else
        {
            //数据库中已经存在任务log
            //首先判断当前任务入职是否为新增任务
            if(messionLogList.size()<2)
            {
                //一定是同一个任务
                if(messionLogList.size() == 0)
                {
                    //新订单,查询最大code码
                    String maxCode = messionLogDao.findMaxCode();
                    if(maxCode.startsWith("0"))
                    {
                        maxCode = maxCode.replaceAll("0","");
                        int m  = Integer.valueOf(maxCode);
                        m++;

                        if(m<10)
                        {
                            maxCode = "000"+String.valueOf(m);
                        }
                        else if(m<100)
                        {
                            maxCode = "00"+String.valueOf(m);
                        }
                        else if(m<1000)
                        {
                            maxCode = "0"+String.valueOf(m);
                        }

                    }
                    else
                    {
                        int m  = Integer.valueOf(maxCode);
                        m++;
                        maxCode = String.valueOf(m);
                    }
                    messionNumber = areaNumber+time+maxCode;
                    messionCode = maxCode;

                    Mession mession = new Mession();
                    mession.setMessionNumber(messionNumber);
                    mession.setCreateTime(new Date());
                    mession.setUpdateTime(new Date());
                    mession.setCarNumber(messionLog.getCarNumber());
                    //如果为open且为新任务则为装车开始
                    if (messionLog.getDoorMessage().equals("open")){
                        mession.setStartOpenDoorTime(new Date());
                        messionDao.save(mession);
                    }
                }
                else
                {
                    messionNumber = messionLogList.get(0).getMessionNumber();
                    messionCode = messionLogList.get(0).getMessionCount();
                }



                messionLog.setCreateTime(new Date());
                messionLog.setUpdateTime(new Date());
                messionLog.setMessionCount(messionCode);

                //判断开关门信息，如果返回open，并且1,2有值，3没值，赋值3；如果返回的close，1有值，2没值，赋值2；3有值，4没值，赋值4；
                if (messionLog.getDoorMessage().equals("open")){
                    //取值mession
                    Mession mession = messionDao.findMessionByMessionNumber(messionNumber);

                    if(mession.getStartCloseDoorTime() != null)
                    {
                        mession.setEndOpenDoorTime(new Date());
                        messionDao.save(mession);
                    }
                }

                if(messionLog.getDoorMessage().equals("close"))
                {
                    Mession mession = messionDao.findMessionByMessionNumber(messionNumber);

                    if(mession.getStartCloseDoorTime() != null)
                    {
                        mession.setEndCloseDoorTime(new Date());
                        messionDao.save(mession);
                    }
                    else
                    {
                        mession.setStartCloseDoorTime(new Date());
                        messionDao.save(mession);
                    }
                }

            }
            else
            {

                //记录大于2了，就有可能出现一天多单的情况，该情况需要判断本次记录距离上一条差多久
                //取最近俩
                MessionLog log1 = messionLogList.get(0);
                MessionLog log2 = messionLogList.get(1);

                Long timec = getDistanceTime(DateTool.Date2String(log1.getCreateTime(),"yyyy-MM-dd HH:mm:ss"),DateTool.Date2String(log2.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));

                if(timec > 10)
                {
                    //新订单,查询最大code码
                    String maxCode = messionLogDao.findMaxCode();
                    if(maxCode.startsWith("0"))
                    {
                        maxCode = maxCode.replaceAll("0","");
                        int m  = Integer.valueOf(maxCode);
                        m++;

                        if(m<1000)
                        {
                            maxCode = "0"+String.valueOf(m);
                        }
                        else if(m<100)
                        {
                            maxCode = "00"+String.valueOf(m);
                        }
                        else if(m<10)
                        {
                            maxCode = "000"+String.valueOf(m);
                        }
                    }
                    else
                    {
                        int m  = Integer.valueOf(maxCode);
                        m++;
                        maxCode = String.valueOf(m);
                    }
                    messionNumber = areaNumber+time+maxCode;

                    messionLog.setCreateTime(new Date());
                    messionLog.setUpdateTime(new Date());
                    messionLog.setMessionCount(messionCode);
                    String rtcTime = messionLog.getRtcTime();

                    Mession mession = new Mession();
                    mession.setMessionNumber(messionNumber);
                    mession.setCreateTime(new Date());
                    mession.setUpdateTime(new Date());
                    mession.setCarNumber(messionLog.getCarNumber());
                    //如果为open且为新任务则为装车开始
                    if (messionLog.getDoorMessage().equals("open")){
                        mession.setStartOpenDoorTime(new Date());
                        messionDao.save(mession);
                    }
                }
                else
                {
                    //旧订单
                    messionNumber = messionLogList.get(0).getMessionNumber();
                    messionCode = messionLogList.get(0).getMessionCount();

                    messionLog.setCreateTime(new Date());
                    messionLog.setUpdateTime(new Date());
                    messionLog.setMessionCount(messionCode);

                    //判断开关门信息，如果返回open，并且1,2有值，3没值，赋值3；如果返回的close，1有值，2没值，赋值2；3有值，4没值，赋值4；
                    if (messionLog.getDoorMessage().equals("open")){
                        //取值mession
                        Mession mession = messionDao.findMessionByMessionNumber(messionNumber);

                        if(mession.getStartCloseDoorTime() != null)
                        {
                            mession.setEndOpenDoorTime(new Date());
                            messionDao.save(mession);
                        }
                    }

                    if(messionLog.getDoorMessage().equals("close"))
                    {
                        Mession mession = messionDao.findMessionByMessionNumber(messionNumber);

                        if(mession.getStartCloseDoorTime() != null)
                        {
                            mession.setEndCloseDoorTime(new Date());
                            messionDao.save(mession);
                        }
                        else
                        {
                            mession.setStartCloseDoorTime(new Date());
                            messionDao.save(mession);
                        }
                    }
                }
            }
        }

        messionLog.setMessionNumber(messionNumber);

        messionLogDao.save(messionLog);

//        //添加新任务，
//        String maxMessionCode = messionDao.findMaxCode
//        messionLog.setMessionNumber(messionNumber);
//        messionLogDao.save(messionLog);
//
//
//        messionLog.setCreateTime(new Date());
//        messionLog.setUpdateTime(new Date());
//        String rtcTime = messionLog.getRtcTime();
//        String s = rtcTime.substring(0, 8);
//        String messionNumber = "";
//        messionNumber = s+messionLog.getCarNumber();
//        List<MessionLog> list = messionLogDao.findMessionLogByMessionNumber(messionNumber);
//        if (list==null || list.size() == 0){
//            Mession mession = new Mession();
//            mession.setMessionNumber(messionNumber);
//            mession.setCreateTime(new Date());
//            mession.setUpdateTime(new Date());
//            mession.setCarNumber(messionLog.getCarNumber());
//            //如果为open且为新任务则为装车开始
//            if (messionLog.getDoorMessage().equals("open")){
//                mession.setStartOpenDoorTime(new Date());
//                messionDao.save(mession);
//            }
//        }else {
//            Mession mession = messionDao.findMessionByMessionNumber(messionNumber);
//            //如果门关且该任务单号的endCloseDoorTime(卸车结束时间)为空则此为装车结束时间
//            if (messionLog.getDoorMessage().equals("close")&&mession.getEndCloseDoorTime()==null){
//                mession.setStartOpenDoorTime(new Date());
//                messionDao.save(mession);
//                //如果门开且该任务单号的startOpenDoorTime(装车开始时间)不为空则此为卸车开始时间
//            }else if (messionLog.getDoorMessage().equals("open")&&mession.getStartOpenDoorTime()!=null){
//                mession.setStartCloseDoorTime(new Date());
//                messionDao.save(mession);
//                //如果门关且该任务单号的endOpenDoorTime(装车结束时间)不为空则此为卸车结束时间
//            }else if(messionLog.getDoorMessage().equals("close")&&mession.getEndOpenDoorTime()!=null){
//                mession.setStartCloseDoorTime(new Date());
//                messionDao.save(mession);
//            }
//        }
//        messionLog.setMessionNumber(messionNumber);
//        messionLogDao.save(messionLog);
        return "ok";
    }


    /**
     * 两个时间相差距离多少天多少小时多少分多少秒
     * @param str1 时间参数 1 格式：1990-01-01 12:00:00
     * @param str2 时间参数 2 格式：2009-01-01 12:00:00
     * @return String 返回值为：xx天xx小时xx分xx秒
     */
    public static Long getDistanceTime(String str1, String str2) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date one;
        Date two;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        try {
            one = df.parse(str1);
            two = df.parse(str2);
            long time1 = one.getTime();
            long time2 = two.getTime();
            long diff ;
            if(time1<time2) {
                diff = time2 - time1;
            } else {
                diff = time1 - time2;
            }
            day = diff / (24 * 60 * 60 * 1000);
            hour = (diff / (60 * 60 * 1000) - day * 24);
            min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
            sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
        } catch (ParseException e) {
            e.printStackTrace();
        }
//        return day + "天" + hour + "小时" + min + "分" + sec + "秒";
        return min;
    }


    /**
     * 装载率解析
     * @param request
     * @param requestBody
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/checkRate", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String checkRate(HttpServletRequest request,@RequestBody String requestBody) throws UnsupportedEncodingException {

        String requestJson = "";
        requestJson = URLDecoder.decode(requestBody, "utf-8");
        requestJson = new String(requestJson.getBytes("ISO-8859-1"), "UTF-8");
        String data = requestJson;

        System.out.print(data);

        /*data = "CarNum,020BY5267$$time,2017-05-26 10:49:46$$1495766986160$$020BY5266$$9$$3$$2700\n" +
                ".0$$0.0$$255.0$$1495766986131$$2017-05-26 10:49:46$$22.643336666666663$$113.8173\n" +
                "9$$ADDR$$MeasureResult,77,MeasureData,1216,1356,1550,1506,1546,1294,1255,1300,12\n" +
                "62,1059,1329,1435,1383,1495,1560,1493,1482,1308,1474,1371,1434,1719,1550,1486,14\n" +
                "60,1313,1034,12844,12592,12343,12853,12597,12594,12856,14135,0,0,0,0,0,27747,295\n" +
                "51,11365,12338,14129,13616,13618,12849,14385,12339,0,0,0,0,0,28783,\n" +
                "$$";*/
        try
        {
            if(!(StringUtils.isEmpty(data)))
            {
                Rate rate = RateUtil.rateHelp(data);

                Rate r = rateDao.findByCarNumberAndGTime(rate.getCarNumber(),rate.getGTime());

                if(r == null)
                {
                    rate.setCreateTime(new Date());
                    rateDao.save(rate);
                }
                else
                {
                    rate.setId(r.getId());
                    rate.setUpdateTime(new Date());
                    rateDao.save(rate);
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return "ok";
    }


    /**
     * 获取指定IP对应的经纬度（为空返回当前机器经纬度）
     *
     * @param ip
     * @return
     */
    public static String[] getIPXY(String ip) {

        String ak = "百度申请的Key";
        if (null == ip) {
            ip = "";
        }

        try {

            URL url = new URL("https://api.map.baidu.com/location/ip?ak=" + ak
                    + "&ip=" + ip + "&coor=bd09ll");
            InputStream inputStream = url.openStream();
            InputStreamReader inputReader = new InputStreamReader(inputStream);
            BufferedReader reader = new BufferedReader(inputReader);
            StringBuffer sb = new StringBuffer();
            String str;
            do {
                str = reader.readLine();
                sb.append(str);
            } while (null != str);


            str = sb.toString();
            if (null == str || str.isEmpty()) {
                return null;
            }


// 获取坐标位子
            int index = str.indexOf("point");
            int end = str.indexOf("}}", index);


            if (index == -1 || end == -1) {
                return null;
            }


            str = str.substring(index - 1, end + 1);
            if (null == str || str.isEmpty()) {
                return null;
            }


            String[] ss = str.split(":");
            if (ss.length != 4) {
                return null;
            }


            String x = ss[2].split(",")[0];
            String y = ss[3];


            x = x.substring(x.indexOf("\"") + 1, x.indexOf("\"", 1));
            y = x.substring(y.indexOf("\"") + 1, y.indexOf("\"", 1));


            return new String[] { x, y };


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }

    /**
     * 获取ip 地址
     *
     * @param
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }


        if(ip.contains(","))
        {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    public String getJson(String urlstr) {
        org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();
        HttpGet method = new HttpGet(urlstr);
        method.setHeader("Content-type" , "application/json");
        HttpResponse response = null;
        try {
            response = httpclient.execute(method);
            if (response != null) {
                // HttpEntity resEntity = response.getEntity();
                return EntityUtils.toString(response.getEntity());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
